#!/bin/bash

# 设置颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # 无颜色

# 基础URL
BASE_URL="http://localhost:3000/api/v1"
TEST_USERNAME="testuser_$(date +%s)"
TEST_EMAIL="${TEST_USERNAME}@example.com"
TEST_PASSWORD="Test@1234"
JWT_TOKEN=""

echo -e "${YELLOW}开始测试学生选课系统API...${NC}"
echo "测试用户: ${TEST_USERNAME}"
echo "测试邮箱: ${TEST_EMAIL}"
echo

# 1. 测试健康检查
echo -e "${YELLOW}1. 测试健康检查${NC}"
HEALTH_RESPONSE=$(curl -s -X GET "${BASE_URL}/health")
echo "响应: ${HEALTH_RESPONSE}"
echo

# 2. 测试用户注册
echo -e "${YELLOW}2. 测试用户注册${NC}"
REGISTER_RESPONSE=$(curl -s -X POST "${BASE_URL}/auth/register" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"${TEST_USERNAME}\",\"password\":\"${TEST_PASSWORD}\",\"email\":\"${TEST_EMAIL}\",\"name\":\"测试用户\",\"role\":\"student\"}")
echo "响应: ${REGISTER_RESPONSE}"
echo

# 3. 测试用户登录
echo -e "${YELLOW}3. 测试用户登录${NC}"
LOGIN_RESPONSE=$(curl -s -X POST "${BASE_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"${TEST_EMAIL}\",\"password\":\"${TEST_PASSWORD}\"}")
echo "响应: ${LOGIN_RESPONSE}"
echo

# 提取JWT令牌
JWT_TOKEN=$(echo ${LOGIN_RESPONSE} | grep -o '"token":"[^"]*' | cut -d'"' -f4)
if [ -n "${JWT_TOKEN}" ]; then
  echo -e "${GREEN}成功获取JWT令牌!${NC}"
else
  echo -e "${RED}无法获取JWT令牌，后续测试可能会失败${NC}"
fi
echo

# 4. 测试获取当前用户信息
echo -e "${YELLOW}4. 测试获取当前用户信息${NC}"
ME_RESPONSE=$(curl -s -X GET "${BASE_URL}/users/me" \
  -H "Authorization: Bearer ${JWT_TOKEN}")
echo "响应: ${ME_RESPONSE}"
echo

# 5. 测试获取所有课程
echo -e "${YELLOW}5. 测试获取所有课程${NC}"
COURSES_RESPONSE=$(curl -s -X GET "${BASE_URL}/courses" \
  -H "Authorization: Bearer ${JWT_TOKEN}")
echo "响应: ${COURSES_RESPONSE}"
echo

# 尝试从课程列表中提取第一个课程ID
COURSE_ID=$(echo ${COURSES_RESPONSE} | grep -o '"id":[0-9]*' | head -1 | cut -d':' -f2)
if [ -z "${COURSE_ID}" ]; then
  COURSE_ID=1
  echo -e "${YELLOW}未找到课程ID，使用默认值: ${COURSE_ID}${NC}"
else
  echo -e "${GREEN}找到课程ID: ${COURSE_ID}${NC}"
fi
echo

# 6. 测试选课
echo -e "${YELLOW}6. 测试选课${NC}"
ENROLL_RESPONSE=$(curl -s -X POST "${BASE_URL}/enrollments" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ${JWT_TOKEN}" \
  -d "{\"courseId\":${COURSE_ID}}")
echo "响应: ${ENROLL_RESPONSE}"
echo

# 7. 测试获取我的选课
echo -e "${YELLOW}7. 测试获取我的选课${NC}"
MY_ENROLLMENTS_RESPONSE=$(curl -s -X GET "${BASE_URL}/enrollments/me" \
  -H "Authorization: Bearer ${JWT_TOKEN}")
echo "响应: ${MY_ENROLLMENTS_RESPONSE}"
echo

# 8. 测试获取所有用户（需要管理员权限，预期会失败）
echo -e "${YELLOW}8. 测试获取所有用户（需要管理员权限）${NC}"
USERS_RESPONSE=$(curl -s -X GET "${BASE_URL}/users" \
  -H "Authorization: Bearer ${JWT_TOKEN}")
echo "响应: ${USERS_RESPONSE}"
echo

# 9. 测试登出
echo -e "${YELLOW}9. 测试用户登出${NC}"
LOGOUT_RESPONSE=$(curl -s -X POST "${BASE_URL}/auth/logout" \
  -H "Authorization: Bearer ${JWT_TOKEN}")
echo "响应: ${LOGOUT_RESPONSE}"
echo

echo -e "${GREEN}测试完成！${NC}"
